/**
 */

package com.bei_en.common.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Formatter;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import com.google.gson.Gson;

/**
 * @author Guocg
 *
 */
public class Mylog {

	public Map map;
	private Logger log;

	public Mylog(Class clazz) {

		log = Logger.getLogger(clazz);
	}

	private HttpServletRequest request;
	private HttpSession session;

	public void trace(Object message) {

		log.trace(new Gson().toJson(map) + "\n" + message);
	}

	public void debug(Object message) {

		log.debug(new Gson().toJson(map) + "\n" + message);
	}

	public void error(Object message) {

		log.error(new Gson().toJson(map) + "\n" + message);
	}

	public void fatal(Object message) {

		log.fatal(new Gson().toJson(map) + "\n" + message);
	}

	public void info(Object message) {

		log.info(new Gson().toJson(map) + "\n" + message);
	}

	public void warn(Object message) {

		log.warn(new Gson().toJson(map) + "\n" + message);
	}

	public HttpServletRequest getRequest() {

		return request;
	}

	private static String getMACAddress(InetAddress ia) {

		// 获得网络接口对象（即网卡），并得到mac地址，mac地址存在于一个byte数组中。
		byte[] mac = null;
		try {
			mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
		} catch (Exception e) {
			System.out.println(e);
		}

		// 下面代码是把mac地址拼装成String
		StringBuffer sb = new StringBuffer();

		Formatter formatter = new Formatter();
		String sMAC = null;
		if (mac != null)
			for (int i = 0; i < mac.length; i++) {
				sMAC = formatter.format(Locale.getDefault(), "%02X%s", mac[i],
						(i < mac.length - 1) ? "-" : "").toString();
			}

		return sMAC;
	}

	public static String getIpAddr(HttpServletRequest request) {

		String ip = request.getHeader("X-Real-IP");
		if (ip == null || ip.length() == 0 && !"unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Forwarded-For");
			if (ip == null || ip.length() == 0
					|| "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("Proxy-Client-IP");
			}
			if (ip == null || ip.length() == 0
					|| "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
			}
			if (ip == null || ip.length() == 0
					|| "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("HTTP_CLIENT_IP");
			}
			if (ip == null || ip.length() == 0
					|| "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("HTTP_X_FORWARDED_FOR");
			}
			if (ip == null || ip.length() == 0
					|| "unknown".equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();

				// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
				if (ip != null && ip.length() > 15) { // "***.***.***.***".length()
					// = 15
					if (ip.indexOf(",") > 0) {
						// ip = ip.substring(0, ip.indexOf(","));
					}
				}
				if (ip.equals("127.0.0.1") || ip.equals("0:0:0:0:0:0:0:1")) {
					// 根据网卡取本机配置的IP
					InetAddress[] inet = null;
					try {
						inet = InetAddress.getAllByName(InetAddress
								.getLocalHost().getHostName());
					} catch (UnknownHostException e) {
						e.printStackTrace();
					}
					for (InetAddress i : inet) {
						if (i.getHostAddress().length() < 16)
							ip += "," + i.getHostAddress();
					}
				}
			}
		}
		return ip;
	}

	public void setRequest(HttpServletRequest request) {

		this.request = request;

		map = new LinkedHashMap();
		String requestUrl = null;
		Map requestPar = null;
		if (request != null) {
			this.session = request.getSession();
			requestUrl = request.getRequestURL().toString();
			requestPar = request.getParameterMap();
			map.put("requestUrl", requestUrl);
			map.put("requestPar", requestPar);
			map.put("clientIp", getIpAddr(request));
			// map.put("USER",
			// session.getAttribute(Constants.AUTHENTICATION_KEY)); // 用户ID
		}
		InetAddress localIp = null;
		try {
			localIp = InetAddress.getLocalHost();
		} catch (UnknownHostException e1) {
			e1.printStackTrace();
		}
		map.put("Server", localIp.toString());
		String localMac = null;
		try {
			localMac = getMACAddress(localIp);
		} catch (Exception e) {
			e.printStackTrace();
		}

		map.put("ServerMac", localMac);

	}

	public HttpSession getSession() {

		return session;
	}

}
